﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Office.Interop.Outlook;
using Microsoft.Win32;
using TeamXpandLicence.ObjectExchange;
using TXLooker.Common;
using TXLooker.Core;
using TXLooker.Hooks;
using TXLooker.Properties;
using Exception = System.Exception;

namespace TXLooker.UI
{
    public partial class RegistrationForm : Form
    {
        public RegistrationForm()
        {
            InitializeComponent();
        }

        public RegistrationForm(Microsoft.Office.Interop.Outlook.Application application)
            : this()
        {
            this.m_application = application;
        }


        private void FillActivationKey()
        {
            if (Clipboard.ContainsText())
            {
                string[] strArray = Clipboard.GetText().Split(new char[] { '-' });
                if ((((strArray.Length == 5) && (strArray[0].Length == 8)) && ((strArray[1].Length == 4) && (strArray[2].Length == 4))) && ((strArray[3].Length == 4) && (strArray[4].Length == 12)))
                {
                    this.m_mskTB1.Text = strArray[0];
                    this.m_mskTB2.Text = strArray[1];
                    this.m_mskTB3.Text = strArray[2];
                    this.m_mskTB4.Text = strArray[3];
                    this.m_mskTB5.Text = strArray[4];
                    DllImportCommon.SetForegroundWindow(base.Handle);
                }
            }
        }

        private void OnClipboardChanged(object sender, ClipboardEventArgs e)
        {
            this.FillActivationKey();
        }

        private void OnClose(object sender, EventArgs e)
        {
            this.m_registrate = false;
            base.Close();
        }

        private void OnClosing(object sender, FormClosingEventArgs e)
        {
            if (this.m_clipboardHook != null)
            {
                this.m_clipboardHook.RemoveHook(false);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.m_clipboardHook = new ClipboardHook();
            this.m_clipboardHook.ClipboardChanged += new ClipboardHook.ClipboardEventHandler(this.OnClipboardChanged);
            this.m_clipboardHook.InstallHook(base.Handle, false);
            this.FillActivationKey();
            base.OnLoad(e);
        }

        private void OnNewEMail(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MailItem item = (MailItem)this.m_application.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem);
            item.To = Resources.LICENSE_E_MAIL;
            item.Display(false);
        }

        private void OnRegistrate(object sender, EventArgs e)
        {
            if ((((this.m_mskTB1.Text.Length != 8) || (this.m_mskTB2.Text.Length != 4)) || ((this.m_mskTB3.Text.Length != 4) || (this.m_mskTB4.Text.Length != 4))) || (this.m_mskTB5.Text.Length != 12))
            {
                MessageBox.Show(this, Resources.STRING_ENTER_VALID_REGISTRATION_KEY, Resources.UI_REGISTRATION, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else
            {
                System.Xml.Serialization.XmlSerializer serializer;
                byte[] buffer;
                string licenceKey = string.Format("{0}-{1}-{2}-{3}-{4}", new object[] { this.m_mskTB1.Text, this.m_mskTB2.Text, this.m_mskTB3.Text, this.m_mskTB4.Text, this.m_mskTB5.Text });
                string macAddress = ApplicationGlobal.MacAddress;
                string str3 = string.Empty;
                Debug.Assert(macAddress != null);
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer = new XmlSerializer(typeof(FullLicenceDataObjectIn));
                    FullLicenceDataObjectIn o = new FullLicenceDataObjectIn(macAddress, licenceKey);
                    serializer.Serialize((Stream)stream, o);
                    buffer = stream.GetBuffer();
                    str3 = Encoding.UTF8.GetString(buffer);
                }
                RegistrationLicenceDataObjectOut @out = null;
                string requestUriString = Resources.STRING_LICENCE_URL + "Registration?FullLicenceDataObjectIn=" + str3;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream stream2 = response.GetResponseStream())
                        {
                            buffer = new byte[response.ContentLength];
                            stream2.Read(buffer, 0, buffer.Length);
                            string xml = Encoding.UTF8.GetString(buffer);
                            if (xml.Replace(" ", string.Empty) == string.Empty)
                            {
                                throw new RegistrationExcepton("Unable get data from server. Check licence key. For futher information contact to TeamXpand support center");
                            }
                            XmlDocument document = new XmlDocument();
                            document.LoadXml(xml);
                            using (TextReader reader = new StringReader(document.InnerText))
                            {
                                serializer = new System.Xml.Serialization.XmlSerializer(typeof(RegistrationLicenceDataObjectOut));
                                @out = (RegistrationLicenceDataObjectOut)serializer.Deserialize(reader);
                            }
                        }
                    }
                }
                catch (RegistrationExcepton excepton)
                {
                    MessageBox.Show(this, excepton.Message, Resources.STRING_REGISTRATION_FAILED);
                    return;
                }
                catch (Exception)
                {
                    MessageBox.Show(this, Resources.STRING_SERVER_UNABLE, Resources.STRING_REGISTRATION_FAILED, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if (!@out.RegistrationOk)
                {
                    MessageBox.Show(this, Resources.STRING_ENTER_INVALID_REG_KEY, Resources.UI_REGISTRATION, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else if ((@out.LicenceType == LicenceType.Trial) || (@out.LicenceType == LicenceType.TrialDaysOff))
                {
                    MessageBox.Show(this, Resources.STRING_ENTER_VALID_REGISTRATION_KEY, Resources.UI_REGISTRATION, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    ApplicationGlobal.LicenceDataProvider.LicenceType = @out.LicenceType;
                    ApplicationGlobal.LicenceDataProvider.DaysOff = @out.TimeLicenceLeft;
                    if (@out.TimeLicenceLeft < 0)
                    {
                        ApplicationGlobal.LicenceDataProvider.LicenceType = LicenceType.FullDaysOff;
                    }
                    Registry.CurrentUser.CreateSubKey(Resources.ACTIVATION_REG_KEY_PATH).SetValue(Resources.ACTIVATION_REG_KEY, licenceKey);
                    MessageBox.Show(this, Resources.STRING_REGISTRATIO_COMPLETE, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    this.Registrate = true;
                    base.Close();
                }
            }
        }

        private void OnTB1TextChanged(object sender, EventArgs e)
        {
            if (this.m_mskTB1.Text.Length >= 8)
            {
                this.m_mskTB2.Focus();
            }
        }

        private void OnTB2TextChanged(object sender, EventArgs e)
        {
            if (this.m_mskTB2.Text.Length >= 4)
            {
                this.m_mskTB3.Focus();
            }
        }

        private void OnTB3TextChanged(object sender, EventArgs e)
        {
            if (this.m_mskTB3.Text.Length >= 4)
            {
                this.m_mskTB4.Focus();
            }
        }

        private void OnTB4TextChanged(object sender, EventArgs e)
        {
            if (this.m_mskTB4.Text.Length >= 4)
            {
                this.m_mskTB5.Focus();
            }
        }

        // Properties
        public bool Registrate
        {
            get
            {
                return this.m_registrate;
            }
            protected set
            {
                this.m_registrate = value;
            }
        }
}
}
